package com.yksj.healthtalk.ui.recharge;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.ChargeRecordEntity;
import com.yksj.healthtalk.entity.ConsumptionHistoryEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 消费与充值明细显示 fragment
 * 
 * @author crj
 * 
 */
public class ChargeRecordFragment extends Fragment implements OnRefreshListener<ListView>{

	public static final int CHARGE_HISTORY=0;
	public static final int CONSUME_HISTORY=1;
	/*  消费历史每页数量 */
	public static final int NUM_PER_PAGE = 20;
	/* 消费历史页号存储 */
	private int pageCount = 1;
	/*  充值历史查询 排序id */
	private int orderId;
	
	private String date = null;
	
	private ListView mListView;
	private int fragmentFlag;
	private ChargeListAdapter adapter;
	/**
	 * 适配器数据存储位置
	 */
	private List<ChargeRecordEntity> chargeMetaData;
	/**
	 * 充值记录明细条数 text
	 */
	private TextView mRecordCountText;
	
	private String recordCountStr;
	private PullToRefreshListView refreshListView;
	protected String ConsumptionSize;//消费记录的总数
	private List<ConsumptionHistoryEntity> ConsumMetaData; //消费记录的总数据
	
	public static ChargeRecordFragment newInstance(int position) {
		ChargeRecordFragment f = new ChargeRecordFragment();
		Bundle mBundle = new Bundle();
		mBundle.putInt("position", position);
		f.setArguments(mBundle);
		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.fragmentFlag = this.getArguments().getInt("position");
		initData();
		
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.charge_record_listview, container,false);
		initView(v);
		return v;
	}

	public void initData() {
		LodingFragmentDialog.showLodingDialog(getFragmentManager(), "马上来了");
		chargeMetaData = new ArrayList<ChargeRecordEntity>();
		ConsumMetaData = new ArrayList<ConsumptionHistoryEntity>();
		adapter = new ChargeListAdapter(this.getActivity(), fragmentFlag);
		switch(fragmentFlag) {
		case CHARGE_HISTORY:
			//第一次加载
			queryChargeHistoryEntity(String.valueOf(Long.MAX_VALUE));
			break;
		case CONSUME_HISTORY:
			queryComsuptionHistoryEntity(pageCount+"");
			break;
		}
	}
	
	/**
	 * 充值历史查询 关联参数 ordId
	 * 请求历史记录
	 * 没有指定日期加载的时候date为null
	 * 第一次加载的时候oride  String.valueOf(Long.MAX_VALUE)表示最大值
	 */
	private void queryChargeHistoryEntity(final String oride){
		HttpRestClient.doHttpQueryChongZhiHostory(SmartFoxClient.getLoginUserId(), oride,date, new AsyncHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, String content) {
				super.onSuccess(statusCode, content);
				LodingFragmentDialog.dismiss(getFragmentManager());
				try {
					JSONObject jsonObject = new JSONObject(content);
					//如果相等，则代表是第一次获取数据。不相等则为下拉刷新获取数据
					if(!String.valueOf(Long.MAX_VALUE).equals(oride)) {
						refreshListView.onRefreshComplete();
						chargeMetaData.addAll(ChargeRecordEntity.parseToListRecord(jsonObject.getJSONArray("datas")));
					}else {
						//第一次数据加载时只需要取等
						chargeMetaData = ChargeRecordEntity.parseToListRecord(jsonObject.getJSONArray("datas"));
					}
					String count = jsonObject.getString("count");
					recordCountStr = getActivity().getResources().getString(R.string.sell_record_info,
							count+"");
//					recordCountStr="消费记录明细 (共 "+count+" 条)";
					mRecordCountText.setText(recordCountStr);
					mRecordCountText.setText(recordCountStr);
					adapter.notifyDataSetChanged();
					if(chargeMetaData.size()>0)
					orderId = Integer.parseInt(chargeMetaData.get(chargeMetaData.size()-1).getId());
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
			@Override
			public void onFailure(Throwable error) {
				LodingFragmentDialog.dismiss(getFragmentManager());
				ToastUtil.showBasicShortToast(getActivity(), "请稍后重试...");
			}
		});
	}
	
	private void initView(View v) {
		refreshListView = (PullToRefreshListView)v.findViewById(R.id.chargeListview);
		mListView = refreshListView.getRefreshableView();
		adapter = new ChargeListAdapter(this.getActivity(),fragmentFlag);
		mListView.setAdapter(adapter);
		mRecordCountText = (TextView) v.findViewById(R.id.recordnum);
		//下拉刷新绑定
		refreshListView.setOnRefreshListener(this);
	}

	//固定刷新20个数据
	protected void queryComsuptionHistoryEntity(final String pageNum) {
		HttpRestClient.doHttpQueryTransactionRecord(SmartFoxClient.getLoginUserId(),date,NUM_PER_PAGE+"",pageNum,new AsyncHttpResponseHandler(){

			@Override
			public void onSuccess(int statusCode, String content) {
				super.onSuccess(statusCode, content);
				try {
					JSONObject object=new JSONObject(content);
					if(!"1".equals(pageNum)) {
						refreshListView.onRefreshComplete();
						ConsumMetaData.addAll(ConsumptionHistoryEntity.parseToList(object.getString("consumRecs")));
					} else {
						ConsumMetaData = ConsumptionHistoryEntity.parseToList(object.getString("consumRecs"));
						ConsumptionSize=object.getString("count");
						//获取json数据中的条数记录 将记录拼到text上面
						recordCountStr = getActivity().getResources().getString(R.string.sell_record_info,
								ConsumptionSize+"");
						mRecordCountText.setText(recordCountStr);
					}
					adapter.notifyDataSetChanged();
					pageCount++;
					LodingFragmentDialog.dismiss(getFragmentManager());
				} catch (JSONException e) {
					refreshListView.onRefreshComplete();
					e.printStackTrace();
				}
			}
			
			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				refreshListView.onRefreshComplete();
				LodingFragmentDialog.dismiss(getFragmentManager());
				ToastUtil.showBasicShortToast(getActivity(), "请稍后重试...");
			}
		});
	}

	public class ChargeListAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		private int flag;
		private Context context;

		public ChargeListAdapter(Context context, int tag) {
			this.flag = tag;
			this.context = context;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			int count = 0;
			switch(flag){
			case 0:
				count = chargeMetaData.size();
				break;
			case 1:
				count = ConsumMetaData.size();
				break;
			}
			return count;
		}

		@Override
		public Object getItem(int position) {
			return ConsumMetaData.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.charge_record_item,
						null);
				holder.chargeContent1 = (TextView) convertView
						.findViewById(R.id.content1);
				holder.chargeDate = (TextView) convertView
						.findViewById(R.id.charge_date);
				holder.chargeContent2 = (TextView) convertView
						.findViewById(R.id.content2);
				holder.chargeTitle2 = (TextView) convertView
						.findViewById(R.id.title2);
				holder.chargeTitle1 = (TextView) convertView.findViewById(R.id.title1);
				holder.chargeNum = (TextView) convertView.findViewById(R.id.charge_temp);
				holder.chargeTemp = (TextView) convertView.findViewById(R.id.charge_record_money_num);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			changeText(this.flag,holder,position);
			return convertView;
		}

		/**
		 * 
		 * @param position fragment处于viewpager内的位置
		 * @param holder adapter内的viewholder
		 * @param viewposition getView方法内position参数
		 */
		public void changeText(int position, ViewHolder holder,int viewposition) {
			String str = "";
			switch (position) {
			case 0://充值历史
				ChargeRecordEntity entity = chargeMetaData.get(viewposition);
				/* 常量改变 */
				holder.chargeTitle1.setText(getStringFromResource(R.string.charge_trade_num));	//交易号
				holder.chargeTitle2.setText(getStringFromResource(R.string.charge_payment));		//交易方式
				/* 从服务器获取 */
				holder.chargeContent1.setText(entity.getTransactionNum());
				holder.chargeContent2.setText(entity.getChargeWay());
				holder.chargeTemp.setText(entity.getChargeNum());
				str = getStringFromResource(R.string.charge_record_time, entity.getChargeTime());
				break;
			case 1://消费历史
				ConsumptionHistoryEntity entity2 = ConsumMetaData.get(viewposition);
				/* 常量改变 */
				holder.chargeTitle1.setText(getStringFromResource(R.string.sell_ussage));	//用途
				holder.chargeTitle2.setText(getStringFromResource(R.string.charge_record_money_num));		//数量
				holder.chargeTitle2.setTextColor(getResources().getColor(	R.color.charge_red));
				holder.chargeContent2.setTextColor(getResources().getColor(R.color.charge_red));
				holder.chargeContent2.setTextSize(15);
				holder.chargeNum.setVisibility(View.INVISIBLE);
				holder.chargeTemp.setVisibility(View.INVISIBLE);
				/* 从服务器获取数据 */
				holder.chargeContent1.setText(entity2.getConsumptionType());
				holder.chargeContent2.setText(entity2.getMoneyNum());
				str = getStringFromResource(R.string.sell_record_time, entity2.getConsumptionTime());
				break;
			}
			holder.chargeDate.setText(str);
		}

		public String getStringFromResource(int resid) {
			return context.getResources().getString(resid);
		}
		
		public String getStringFromResource(int resid,String str1) {
			return context.getResources().getString(resid,str1);
		}
		
		private class ViewHolder {
			private TextView chargeDate;//成交时间
			private TextView chargeContent1;//交易时间
			private TextView chargeContent2;//交易方式
			private TextView chargeTitle2;//标题2
			private TextView chargeTitle1;//标题1
			private TextView chargeNum;//数量
			private TextView chargeTemp;//标题3
		}
	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		switch(fragmentFlag) {
		case 0:
			queryChargeHistoryEntity(orderId+"");
			break;
		case 1:
			queryComsuptionHistoryEntity(pageCount+"");
			break;
		}
	}
	
	//当外部activity设置完时间之后调用此方法更新fragment数据
	public void onDateSetRefresh(int position,String date) {
		this.date = date;
		switch(position) {
		case CHARGE_HISTORY:
			chargeMetaData.clear();
			adapter.notifyDataSetChanged();
			queryChargeHistoryEntity(String.valueOf(Long.MAX_VALUE));
			break;
		case CONSUME_HISTORY:
			ConsumMetaData.clear();
			adapter.notifyDataSetChanged();
			pageCount = 1;
			queryComsuptionHistoryEntity(pageCount+"");
			break;
		}
	}
	
}
